﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace WinformMqttDemo
{
    public partial class Form1 : Form
    {

        MqttClient client = new MqttClient(IPAddress.Parse("127.0.0.1"));//MQTT_BROKER_ADDRESS

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            client.Subscribe(new string[] { "/user/update" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE }); // sub 的qos=1

            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId);
        }

        private void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            //设备返回的数据在 e.Message 中
            //Console.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);

            this.Invoke(new EventHandler(delegate {
                tbRec.Text += e.Topic + ":\r\n";
                tbRec.Text += Encoding.GetEncoding("GB2312").GetString( e.Message);
            }));

            this.Invoke(new EventHandler(delegate
            {
                tbRec.SelectionStart = tbRec.Text.Length;
                tbRec.ScrollToCaret();
            }));
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string cmd = tbSend.Text.Trim() + "\r\n";
            client.Publish("/user/get", Encoding.UTF8.GetBytes(cmd), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
        }
    }
}
